import React, { Component } from 'react';
import App from 'layout/App.js'
import CommonModal from './../../components/CommonModal/index.jsx';
import SearchListItem from './../../components/SearchListItem/index.jsx';
import { FormControl, Button, Table, Select, Dropdown, Tree, Breadcrumb, AutoComplete, Upload, Col, Row } from 'tinper-bee';
import {
	getWorkGanttProgress,
	getWorkGanttTable,
	InsertWorkGanttItem,
	getWorkGanttManager,
	deleteWorkGanttItem,
	updateWorkGanttItem,
	getUserBaseDataUrl,
	getWorkGanttDependName,
	getDepartmentData,
	getOrgData,
	getPlanTemplet
} from './workgantt.config.js';
import { vendorsDanger as danger, vendorsWarning as warning, vendorsFmtDate } from './../../utils/config';
import { onTreeNodeSelect } from '../WorkGanttAdd/index';
// 参照相关
import { handeUpdateTableData } from './../CustomTemplateConst/index';
import ReferEditCell from './../../components/ReferEditCell/index.jsx';
import { getMilestoneRef, getBillTypeRef, getManagerRef } from './../CustomTemplateConst';

const Option = Select.Option;
import './index.less';
import DatePicker from 'bee-datepicker';
import moment from 'moment';
moment.locale('zh-cn');
const format = "YYYY-MM-DD";
const TreeNode = Tree.TreeNode;
import zhCN from "rc-calendar/lib/locale/zh_CN";
import enUS from "rc-calendar/lib/locale/en_US";
let timer = null;
let loopAddStatus = '';
let saveItem = null;
let isNameFlag = true;
let importConfig = null;


let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if (cookieStr) {
	tenantId = cookieStr.split('=')[1];
}
// let tenantId = "x61tnmfx";
import CommonTreeReferStruc from "./../../components/ReferTreeStruc/index.js";
export default class CustomTemplateAdd extends Component {
	constructor(props) {
		super(props);
		this.state = {
			userName: '',
			currenTime: new Date().getTime(),
			projectList: [],
			parentProjectKey: '',
			newItemData: {
				code: '1',
				name: null,
				dependPlanName: '',
				planDays: 1,  // 工期数据
				pkMilestone: '', // 里程碑档案
				relatedBillType: '', // 单据关联
				departmentName: '',//负责部门
				manager: '', // 负责人档案，
				key: new Date().getTime(),
				isFirst: true
			},
			tableData: [],
			showModal: false,
			modalContext: '',
			modalSize: '',
			treeNodeData: [],
			modalTitle: '',
			oneButton: false,
			oneButtonText: '',
			handlerModalConfirm: null,
			handlerModalClose: null,
			dependName: '',
			record: null,
			firstTreeName: '',
			createStatus: false,
			managerList: [],
			managerText: '1',
			chooseTableIndex: null,
			isEmptyFirstName: false,
			chooseManagerItem: '',
			oneButtonClassName: '',
			importConfig: null,
			importValue: undefined,
			isFirstAddSame: true,
			expandedRowKeys: [],
			refMileStoneDataSource: [], // 里程碑参照数据 
			refBillTypeDataSource: [], // 单据类型参照数据
			refManagerSource: [], // 负责人参照数据
			departmentData: [],//责任部门参照数据
			plantypeData: [],//计划类型参照数据
			refPlantypeId: [],//计划类型id
			refPlantypeItem: [],//选择项得计划类型得数据
			typeName: '',//计划类型名称
			type: '',//计划类型主键
			orgData: [],//组织参照数据
			refOrgId: [],//组织id
			refOrgName: [],//组织名称
			refOrgItem: [],//选择项得组织得数据,
			initalData: [],
		}
	}
	componentDidMount() {
		this.init();
	}
	getProjectFileProps = () => {
		let _me = this;
		return {
			name: 'file',
			action: '/schedule/template/importProject',
			accept: "*.mpp",
			showUploadList: false,
			data: {
				name: _me.state.firstTreeName,
				pkProject: _me.state.parentProjectKey,
				childCount: _me.getChildCount(_me.state.tableData)
			},
			headers: {},
			onChange(info) {
				if (info.file.status === 'done') {
					if (info.file.response.resultCode === 'ok') {
						let data = info.file.response.result;
						_me.state.tableData.forEach((item, index) => {
							if (item.name === null || item.name === '') {
								_me.state.tableData.splice(index, 1);
							}
						})
						_me.state.tableData.push(...data);
						_me.formatTableData(_me.state.tableData);
						_me.state.tableData.forEach((item, index) => {
							item['isFirst'] = true;
						})
						loopAddStatus = '';
						let dependPlanMap = new Map();
						// 制造scode, 重置loopAddStatus
						_me.refreshDependPlanName(_me.state.tableData, dependPlanMap, null);
						_me.setState({
							tableData: _me.state.tableData
						});
					} else {
						danger({ text: info.file.response.exMsg });
					}
				} else if (info.file.status === 'error') {
					console.log(`${info.file.name} file upload failed.`);
				}
			}
		}
	}

	// 获取里程碑参照  
	getMilestoneRef = () => {
		getMilestoneRef({ pkTenant: tenantId }).then((res) => {
			let { resultCode, result, exMsg } = res.data;
			if (resultCode !== "busi_ex") {
				this.setState({ refMileStoneDataSource: result });
			} else {
				danger({ text: exMsg });
			}
		});
	}

	// 获取里程碑单据参照
	getMilestoneBillRef = () => {
		getBillTypeRef().then((res) => {
			let { resultCode, result, exMsg } = res.data;
			if (resultCode !== "busi_ex") {
				this.setState({ refBillTypeDataSource: result });
			} else {
				danger({ text: exMsg });
			}
		});
	}

	// 获取负责人参照数据
	getPageManagerRef = () => {
		getManagerRef().then((res) => {
			let { resultCode, result, exMsg } = res.data;
			if (resultCode !== "busi_ex") {
				this.setState({ refManagerSource: result });
			} else {
				danger({ text: exMsg });
			}
		});
	}

	// 监听参照框数据变化
	referInputChange = (key, rec, index) => value => {
		// 整合table数据
		handeUpdateTableData(value, key, rec, index, this.state.tableData, this.updateTableDataCallback);
	}

	getExcelFileProps = () => {
		let _me = this;
		return {
			name: 'file',
			action: '/schedule/template/importFromExcel',
			accept: "*.xlsx",
			showUploadList: false,
			data: {
				name: _me.state.firstTreeName,
				pkProject: _me.state.parentProjectKey,
				childCount: _me.getChildCount(_me.state.tableData)//_me.state.tableData.length
			},
			headers: {},
			onChange(info) {
				if (info.file.status === 'done') {
					if (info.file.response.resultCode === 'ok') {
						let data = info.file.response.result;
						_me.state.tableData.forEach((item, index) => {
							if (item.name === null || item.name === '') {
								_me.state.tableData.splice(index, 1);
							}
						})
						_me.state.tableData.push(...data);
						_me.formatTableData(_me.state.tableData);
						_me.state.tableData.forEach((item, index) => {
							item['isFirst'] = true;
						})
						loopAddStatus = '';
						let dependPlanMap = new Map();
						// 制造scode, 重置loopAddStatus
						_me.refreshDependPlanName(_me.state.tableData, dependPlanMap, null);

						_me.setState({
							tableData: _me.state.tableData
						});
					} else {
						danger({ text: info.file.response.exMsg });
					}
				} else if (info.file.status === 'error') {
					console.log(`${info.file.name} file upload failed.`);
				}
			}
		}
	}
	getChildCount = (data) => {
		let count = 0;
		data.forEach((item, index) => {
			if (item.name !== null && item.name !== '') {
				count = ++count;
			}
		})
		return count;
	}
	init = () => {
		// 获取创建人信息
		getUserBaseDataUrl({},
			res => {
				let userName = res.data.result.userName;
				this.state.tableData.push(this.state.newItemData);
				this.setState({
					userName,
					tableData: this.state.tableData
				})
			},
			error => { }
		);

	}
	handlerSetFirstLevelTreeName = (e) => {
		let value = e.target.value;
		if (value.length >= 50) {
			value = value.substring(0, 50);
		}
		this.setState({
			fileProps: Object.assign({}, this.state.fileProps, { data: { name: value } }),
			firstTreeName: value
		});
	}
	handlerSaveAddTree = () => {
		// 判断是否根级别树结构名称为空（必输项）
		if (this.state.firstTreeName.trim() === '') {
			this.setState({
				isEmptyFirstName: true
			});
			return;
		} else {
			this.setState({
				isEmptyFirstName: false,
				initalData: JSON.parse(JSON.stringify(this.state.tableData))	//保留初始数据， 以防失败
			}, () => {

				// 合成最后需要的树状结构数据
				let lastTreeData = [];
				this.formatTableData(this.state.tableData, false, "save");

				let delectArray = [];
				let firstTreeLevelDataMock = {
					'name': this.state.firstTreeName,
					'pkOrg': "" + this.state.refOrgId + "",
					'type': "" + this.state.refPlantypeId + "",
					'code': 0,
					'delectArray': delectArray,
					'scheduleTemplateItemVOS': this.state.tableData
				};
				//请求插入数据接口
				InsertWorkGanttItem(firstTreeLevelDataMock,
					res => {
						let data = res.data;
						if (data.resultCode === 'ok') {
							window.location.href = "./customtemplate.html";
						} else {
							danger({ text: data.exMsg });
							this.setState({
								tableData: [...this.state.initalData]
							})
						}
					},
					error => {

					}
				)
			});

		}

	}
	formatTableData = (data, flag = true, source) => {
		data.forEach((item, index) => {
			if (source === "save") {
				item['pkDepartment'] = item['pkDepartment'] ? "" + item['pkDepartment'] + "" : '';
				delete item['departmentItem'];
				delete item['departmentName'];
			} else {
				item["departmentName"] = item["departmentName"] ? typeof item.departmentName === "string" ? [item["departmentName"]] : item["departmentName"] : [];
				item["pkDepartment"] = item["pkDepartment"] ? typeof item.pkDepartment === "string" ? [item["pkDepartment"]] : item["pkDepartment"] : [];
			}

			if (!flag) {
				if (item.name === null) {
					data.splice(index, 1);
				}
			}
			if (item.children) {
				this.formatTableData(item.children, flag, source);
			}
			// 如果里程碑为空，则关联单据清空
			if (item.pkMilestone === "") {
				item.relatedBillType = "";
			}
			item['key'] = item['code'] + Math.random();
		})
	}
	handlerLeaveAddPage = () => {
		window.location.href = "./customtemplate.html";
	}
	handlerNoChangeAddPage = () => {
		this.setState({
			showModal: false
		})
	}
	// 跳转回浏览页面
	handlerCancelAddTree = () => {
		this.setState({
			showModal: true,
			handlerModalConfirm: this.handlerLeaveAddPage,
			handlerModalClose: this.handlerNoChangeAddPage,
			modalContext: 'cancel'
		});
	}

	// 工期、里程碑字段修改后，更新表格数据
	updateTableDataCallback = (value) => {
		this.setState({ tableData: value });
	}

	handlerSaveChange = (e, flag, rec) => {
		if (flag === 'createSon' || flag === 'createSame') {
			isNameFlag = false;
			this.findEmptyName(this.state.tableData);

			// 限制没有输入名字后继续创建树节点
			if (isNameFlag) {
				warning({ text: "有存在名称为空的计划，不能继续创建树节点！" });
				return;
			}
		}
		if (flag === 'createSon') {
			if (this.state.record.name === null || this.state.record.name === '') {
				warning({ text: "计划名称不能为空！" });
				return;
			}
			// 只有末级节点才可以关联单据类型
			if (this.state.record.relatedBillType !== "") {
				warning({ text: "只有末级节点可以关联单据类型！" });
				return;
			}
			// 判断children是否已经定义过
			if (rec['children'] === undefined || rec['children'] === null) {
				rec['children'] = [];
			}
			rec['children'].push({
				code: '',
				name: null,
				planDays: 1,  // 工期数据
				pkMilestone: "", // 里程碑档案
				relatedBillType: '', // 单据关联
				manager: '', // 负责人档案,
				departmentName: '',//责任部门
				dependPlanName: '',
				key: new Date().getTime()
			})

			// 创建子级时候自动打开
			this.setState({
				expandedRowKeys: [this.state.record.key, ...this.state.expandedRowKeys]
			})

		} else if (flag === 'createSame') {
			if (this.state.record.name === null || this.state.record.name === '') {
				return;
			}
			if (this.state.isFirstAddSame) {
				this.setState({
					isFirstAddSame: false
				})
				//vendorsDanger({'text': '前置计划将会被清空！'});
			}
			if (this.state.record.isFirst) {
				this.state.tableData.splice(parseInt(this.state.record.code), 0, {
					code: '',
					name: null,
					planDays: 1,  // 工期数据
					pkMilestone: "", // 里程碑档案
					relatedBillType: '', // 单据关联
					manager: '', // 负责人档案
					departmentName: '',//负责部门
					dependPlanName: '',
					key: new Date().getTime(),
					isFirst: true
				})
			} else {
				saveItem = null;
				//原代码， 但1.1一直加同级， 加到1.10，再继续加同级， 1.11加不上，报错
				//this.findTreeParent(this.state.tableData ,this.record.code.substring(0, this.record.code.length - this.record.code.split('.')[0].length -1), (item)=>{ saveItem = item});
				// saveItem['children'].splice(parseInt(this.state.record.code.split('.')[this.state.record.code.split('.').length - 1]), 0, {
				//修改后
				this.findTreeParent(this.state.tableData, this.state.record.code.slice(0, this.state.record.code.lastIndexOf(".")), (item) => { saveItem = item });
				saveItem['children'].push({
					code: '',
					name: null,
					planDays: 1,  // 工期数据
					pkMilestone: "", // 里程碑档案
					relatedBillType: '', // 单据关联
					manager: '', // 负责人档案
					departmentName: '',//负责部门
					dependPlanName: '',
					key: new Date().getTime()
				})
			}
			//this.handlerClearDenpendName(this.state.tableData);

		} else if (flag === 'departmentName') {
			rec['pkDepartment'] = e.id;
			rec['departmentName'] = e.title;
			rec['departmentItem'] = e.item;
		} else if (flag === 'dependName') {
			rec['dependPlanName'] = e;
		} else {
			let value = e.target.value;
			if (value.length >= 50) {
				value = value.substring(0, 50);
			}
			rec[flag] = value;
		}

		// 制造scode, 重置loopAddStatus
		let dependPlanMap = new Map();
		// 制造scode, 重置loopAddStatus
		this.refreshDependPlanName(this.state.tableData, dependPlanMap, null);

		this.setState({
			tableData: this.state.tableData
		});
	}

	refreshDependPlanName = (data, dependPlanMap, deleteScode) => {
		this.setCodeLoop(data, dependPlanMap, deleteScode);
		this.getDependPlanLoop(data, dependPlanMap);
	}

	getDependPlanLoop = (data, dependPlanMap) => {
		data.forEach((item, index) => {
			item["departmentName"] = item["departmentName"] ? typeof item.departmentName === "string" ? [item["departmentName"]] : item["departmentName"] : [];
			item["pkDepartment"] = item["pkDepartment"] ? typeof item.pkDepartment === "string" ? [item["pkDepartment"]] : item["pkDepartment"] : [];
			if (item['dependPlanName']) {
				if (dependPlanMap.has(item['dependPlanName'])) {
					item['dependPlanName'] = dependPlanMap.get(item['dependPlanName']);
				}
			}
			if (item.children) {
				this.getDependPlanLoop(item.children, dependPlanMap);
			}
		})
	}
	setCodeLoop = (data, dependPlanMap, deleteScode) => {
		let currentScode = '';
		data.forEach((item, index) => {
			let origScode = item.code;
			if (item.isFirst) {
				item.code = String(index + 1);
			} else {
				if (currentScode === '') {
					item.code = loopAddStatus + '.' + (index + 1);
				} else {
					item.code = currentScode.substring(0, currentScode.length - (String(index).length + 1)) + '.' + (index + 1);
				}
			}

			currentScode = item.code;
			if (origScode !== currentScode) {
				dependPlanMap.set(origScode, currentScode);
			}

			if (item.dependPlanName && deleteScode !== null && (item.dependPlanName + '.').startsWith(deleteScode + '.')) {
				item.dependPlanName = undefined;
			}

			if (item.children) {
				loopAddStatus = String(item.code);
				this.setCodeLoop(item.children, dependPlanMap, deleteScode);
			}
		})
	}
	findTreeParent = (data, code, callback) => {
		data.forEach((item, index) => {
			if (item.code === code) {
				callback(item);
			} else {
				if (item.children) {
					this.findTreeParent(item.children, code, callback);
				}
			}
		})
	}
	handlerDeleteItem = (index, rec) => {
		//vendorsDanger({'text': '前置计划将会被清空！'});
		setTimeout(() => {
			if (rec.isFirst) {
				this.state.tableData.splice(index, 1);
			} else {
				this.findTreeParent(this.state.tableData,
					this.state.record.code.substring(0, this.state.record.code.length - 2),
					(item) => {
						item['children'].splice(index, 1)
						if (item['children'].length === 0) {
							item['children'] = null;
						}
					})
			}

			// 删除之后重新排序scode字段
			loopAddStatus = '';
			let dependPlanMap = new Map();
			// 制造scode, 重置loopAddStatus
			this.refreshDependPlanName(this.state.tableData, dependPlanMap, this.state.record.code);
			if (this.state.tableData === null || this.state.tableData.length === 0) {
				this.state.tableData.push({
					code: '1',
					name: null,
					dependPlanName: '',
					departmentName: '',//责任部门
					key: new Date().getTime(),
					isFirst: true
				});
			}
			this.setState({
				tableData: this.state.tableData
			})
		}, 0);
	}
	handlerClearDenpendName = (data) => {
		data.forEach((item, index) => {
			item['dependPlanName'] = null;
			if (item.children) {
				this.handlerClearDenpendName(item.children);
			}
		})
	}
	handlerDeleteConfirm = () => {
		this.setState({
			showModal: false
		});
	}
	handlerDeleteClose = () => {
		this.setState({
			showModal: false
		});
	}
	handlerChooseDependName = () => {
		getWorkGanttDependName({ rootId: this.state.pkRootId },
			res => {
				this.setState({
					treeNodeData: res.data.result,
					showModal: true,
					modalSize: 'lg',
					modalTitle: '前置计划',
					oneButton: true,
					oneButtonText: '确定',
					handlerModalConfirm: this.handlerSaveDependName,
					modalContext: 'dependName',
					oneButtonClassName: 'large-btn'
				});
			},
			error => {

			})
	}

	// 清空前置计划
	clearDependName = () => {
		this.setState({ dependName: "" }, () => {
			this.handlerSaveChange("", 'dependName', this.state.record);
		});
	}

	handlerSaveDependName = () => {
		this.handlerSaveChange(this.state.dependName, 'dependName', this.state.record)
		this.setState({
			showModal: false
		});
	}
	handlerSaveManager = () => {
		this.handlerSaveChange(this.state.chooseManagerItem, 'manager', this.state.record)
		this.setState({
			showModal: false
		});
	}
	handlerChooseManager = () => {
		this.setState({
			showModal: true,
			oneButton: true,
			modalSize: 'lg',
			modalTitle: '选择负责人',
			oneButton: true,
			oneButtonText: '确定',
			handlerModalConfirm: this.handlerSaveManager,
			modalContext: 'manager',
			oneButtonClassName: 'large-btn'
		});
		this.managerSearch('');
	}
	onChooseManagerItem = item => {
		this.setState({
			chooseManagerItem: item,
			managerText: item.userName
		});

	}
	managerSearch = (keyword) => {
		clearTimeout(timer);
		timer = setTimeout(() => {
			getWorkGanttManager({ keyword: keyword, projectId: this.state.parentProjectKey },
				res => {
					let data = res.data.result;
					data.forEach((item, index) => {
						item['name'] = item['userName'];
					})
					this.setState({
						managerList: data,
						managerText: keyword
					});
				},
				error => { }
			);
		}, 300)
	}
	getModalContent = (flagStatus) => {
		let modalContext = '';

		switch (flagStatus) {
			case 'dependName':
				const loop = data => data.map((item) => {
					let innerName = item.name === null ? '' : item.name;
					if (item.children && item.children.length) {
						return <TreeNode key={item.key} title={item.code + ' ' + innerName}>{loop(item.children)}</TreeNode>;
					}
					return <TreeNode key={item.key} title={item.code + ' ' + innerName} />;
				});
				return <Tree onSelect={onTreeNodeSelect.bind(this)}>
					{loop(this.state.tableData)}
				</Tree>
				break;
			case 'manager':
				return <div className="manager-content">
					<SearchListItem data={this.state.managerList}
						onChange={this.managerSearch}
						onChoose={this.onChooseManagerItem}
						defaultValue={this.state.managerText}
						placeholder={'输入姓名'}
						showTotalNumber={true}
					></SearchListItem>
				</div>

				break;
			case 'cancel':
				return <p>一旦执行，所填信息都将丢失！是否确认？</p>
		}
	}
	findEmptyName = (data) => {
		for (let i = 0; i < data.length; i++) {
			if (data[i].name === '' || data[i].name === null) {
				isNameFlag = true;
			} else {
				if (data[i].children) {
					this.findEmptyName(data[i].children);
				}
			}
		}
	}
	handlerShowAddTree = (rec) => {
		isNameFlag = false;
		this.findEmptyName(this.state.tableData);

		// 限制没有输入名字后继续创建树节点
		if (!rec.name || rec.name === "") {
			warning({ text: "有存在名称为空的计划，不能继续创建树节点！" });
			return;
		}
		this.setState({
			createStatus: true
		});
	}
	handlerCloseAddTree = () => {
		this.setState({
			createStatus: false
		});
	}
	getColumns = () => {
		let _me = this;
		return [
			{
				title: "计划名称",
				dataIndex: "name",
				key: "name",
				width: '30%',
				render(text, rec, index) {
					return <div className="sname-container clearfix">
						<i>{rec.code}</i>
						<FormControl value={rec.name}
							placeholder={'请输入'}
							onChange={(e) => { _me.handlerSaveChange(e, 'name', rec) }}
							className={rec.isEmptyName ? 'danger' : ''} />
					</div>

				}
			},
			{
				title: "前置计划",
				dataIndex: "dependPlanName",
				key: "dependPlanName",
				width: '10%',
				render(text, rec, index) {
					return <div className="depend-container">
							<div className="choose-style" onClick={_me.handlerChooseDependName}>
								<span className="depend-style">{text}</span>
								{text ? null : <i className="uf uf-check-s-2"></i>}
							</div>
							{text ? <i className="uf uf-close-c close-icon-style" onClick={_me.clearDependName}></i> : null}
						</div>
				}
			},
			{
				title: "工期",
				dataIndex: "planDays",
				key: "planDays",
				width: '10%',
				render(text, rec, index) {
					return <div className="sname-container clearfix">
						<FormControl value={text}
							placeholder={'请输入正整数'}
							type="number"
							onChange={(value) => { handeUpdateTableData(value, "planDays", rec, index, _me.state.tableData, _me.updateTableDataCallback) }} />
					</div>
				}
			},
			{
				title: "里程碑",
				className: "plan-table-text-center",
				children: [
					{
						title: "里程碑档案",
						dataIndex: "pkMilestone",
						key: "pkMilestone",
						width: 100,
						className: "plan-table-text-center",
						render(text, rec, index) {
							return (
								<ReferEditCell
									title="里程碑档案"
									value={rec.milestoneName}
									sourceKey="pkMilestone"
									refDataSource={_me.state.refMileStoneDataSource}
									getRef={_me.getMilestoneRef}
									onChange={_me.referInputChange("pkMilestone", rec, index)} />
							)
						}
					},
					{
						title: "里程碑单据",
						dataIndex: "relatedBillType",
						key: "relatedBillType",
						width: 100,
						className: "plan-table-text-center",
						render(text, rec, index) {
							if (rec.pkMilestone === "") {
								return (
									null
								);
							} else {
								return (
									rec.children ? null : <ReferEditCell title="里程碑单据" value={rec.relatedBillTypeName} sourceKey="relatedBillType" refDataSource={_me.state.refBillTypeDataSource} getRef={_me.getMilestoneBillRef} onChange={_me.referInputChange("relatedBillType", rec, index)} />
								)
							}
						}
					}
				]
			},
			{
				title: "责任部门",
				dataIndex: "departmentName",
				key: "departmentName",
				width: '10%',
				render(text, rec, index) {
					return (
						<CommonTreeReferStruc
							referType={"tree"}
							data={_me.state.departmentData}
							selectedKeysId={rec.pkDepartment}
							selectedKeysName={rec.departmentName}
							handleSelectedKeys={(data) => _me.handleSelectedKeys(data, "departmentName")}
							isShowSearchArea={false}
							title={"责任部门"}
							getData={_me.getDepartmentData}
							sname={"name"}
							scode={"code"}
							pk={"pkDept"}
							children={"children"}
						/>
					)
				}
			},
			{
				title: "负责人",
				dataIndex: "manager",
				key: "manager",
				width: '10%',
				className: "plan-table-text-center",
				render(text, rec, index) {
					return (
						<ReferEditCell
							value={rec.managerName}
							title="负责人"
							sourceKey="manager"
							refDataSource={_me.state.refManagerSource}
							getRef={_me.getPageManagerRef}
							onChange={_me.referInputChange("manager", rec, index)} />
					)
				}
			},
			{
				title: "操作",
				dataIndex: "play",
				className: "operate-style",
				key: "play",
				width: 140,
				render(text, rec, index) {
					return <div className="creact-group">
						<a href="javascript:;" onClick={() => { _me.handlerShowAddTree(rec) }}>
							添加
						<i className="uf uf-triangle-down"></i>
							{
								_me.state.createStatus && _me.state.record.key === rec.key && <ul className="create-btn" onMouseLeave={_me.handlerCloseAddTree}>
									<li>
										<a href="javascript:;" onClick={(e) => { _me.handlerSaveChange(e, 'createSame', rec) }}>创建同级</a>
									</li>
									<li>
										<a href="javascript:;" onClick={(e) => { _me.handlerSaveChange(e, 'createSon', rec) }}>创建子级</a>
									</li>
								</ul>
							}
						</a>
						<span className="line">|</span>
						<a href="javascript:;" onClick={(e) => { _me.handlerDeleteItem(index, rec) }}>删除</a>
					</div>
				}
			}
		]
	}
	getDepartmentData = () => {
		let _me = this;
		let pkOrg = _me.state.refOrgItem[0] ? _me.state.refOrgItem[0].pkOrganization : null;
		getDepartmentData({ pkOrg },
			res => {

				let data = res.data.result;
				_me.setState({
					departmentData: [...data]
				})
			},
			error => {
			}
		)

	}
	getOrgData = () => {
		getOrgData({},
			res => {
				let data = res.data.result;
				this.setState({
					orgData: [data]
				})
			},
			error => {
			}
		)

	}
	getPlanTypeData = () => {

		getPlanTemplet({},
			res => {
				let data = res.data.result;
				this.setState({
					plantypeData: [...data]
				})
			},
			error => {
			}
		)

	}
	handleSelectedKeys = (data, node) => {
		if (node === "planType") {
			this.setState({
				type: data.title,
				refPlantypeId: data.id,
				refPlantypeItem: data.item
			});
		} else if (node === "org") {
			this.setState({
				refOrgName: data.title,
				refOrgId: data.id,
				refOrgItem: data.item
			});
		} else {
			this.handlerSaveChange(data, node, this.state.record)
		}

	}
	onRowClick = (record, index, event) => {
		this.setState({
			record,
			chooseTableIndex: index
		});
	}
	onhide = () => {
		this.setState({
			showModal: false
		});
	}
	handlerChooseImportWay = () => {
		this.setState({
			importValue: undefined
		});
	}
	onExpand = (expanded, record) => {
		if (this.state.expandedRowKeys.indexOf(record.key) !== -1) {
			this.state.expandedRowKeys.forEach((item, index) => {
				if (item === record.key) {
					this.state.expandedRowKeys.splice(index, 1)
				}
			})
		} else {
			this.state.expandedRowKeys.push(record.key)
		}

		this.setState({
			expandedRowKeys: this.state.expandedRowKeys
		});
	}
	handlerSetempType = (e) => {
		this.setState({
			type: e.target.value
		})
	}
	render() {
		let {
			userName,
			currenTime,
			parentProjectKey,
			projectList,
			tableData,
			showModal,
			modalContext,
			modalSize,
			modalTitle,
			oneButton,
			oneButtonText,
			oneButtonClassName,
			importValue,
			orgData,
			refOrgId,
			refOrgName,
			plantypeData,
			refPlantypeId,
			type
		} = this.state;
		return (
			<App>
				<CommonModal show={showModal}
					cancel={this.state.handlerModalClose}
					confirm={this.state.handlerModalConfirm}
					hide={this.onhide}
					content={this.getModalContent(modalContext)}
					backdrop={true}
					size={modalSize}
					title={modalTitle}
					oneButton={oneButton}
					oneButtonText={oneButtonText}
					oneButtonClassName={oneButtonClassName}
				>
				</CommonModal>
				<div className="header clearfix">
					<Breadcrumb>
						<Breadcrumb.Item href="./customtemplate.html">
							计划模板
					    </Breadcrumb.Item>
						<Breadcrumb.Item href="./customtemplateadd.html">
							创建计划模板
					    </Breadcrumb.Item>
					</Breadcrumb>
					<div className="header__create--context">
						<span>创建人：{userName}</span>
						<span>创建时间：{vendorsFmtDate(currenTime)}</span>
					</div>
				</div>
				<div className="content">
					<div className="content-header clearfix">
						<h6>基本信息</h6>
						<div className="header__btn">
							<Button colors="primary" onClick={this.handlerSaveAddTree}>保存</Button>
							<Button className="cancel-btn" onClick={this.handlerCancelAddTree}>取消</Button>
						</div>
					</div>
					<Row>
						<div className="content-select clearfix">
							<div className="project-name">
								<span className="name">组织名称：</span>
								<CommonTreeReferStruc
									referType={"tree"}
									data={orgData}
									selectedKeysId={refOrgId}
									selectedKeysName={refOrgName}
									handleSelectedKeys={(data) => this.handleSelectedKeys(data, "org")}
									isShowSearchArea={false}
									title={"组织名称"}
									getData={this.getOrgData}
									sname={"sname"}
									scode={"scode"}
									pk={"pkOrganization"}
									children={"children"}
								/>
							</div>
							<div className="project-name">
								<span className="name">计划类型：</span>
								<CommonTreeReferStruc
									referType={"tree"}
									data={plantypeData}
									selectedKeysId={refPlantypeId}
									selectedKeysName={type}
									handleSelectedKeys={(data) => this.handleSelectedKeys(data, "planType")}
									isShowSearchArea={false}
									title={"计划类型"}
									getData={this.getPlanTypeData}
									sname={"sname"}
									scode={"scode"}
									pk={"pkProjectType"}
									children={"projectTypeVOS"}
								/>
							</div>
							<div className="default__project--item">
								<span className="name">*模板名称：</span>
								<FormControl size="lg" placeholder={'请输入'} value={this.state.firstTreeName} onChange={this.handlerSetFirstLevelTreeName} className={this.state.isEmptyFirstName ? 'danger-border' : ''} />
							</div>
							<div className="import-project">
								<Select size="lg" placeholder={'导入计划'} onSelect={this.handlerChooseImportWay} value={importValue}>
									<Option value="0">
										<Upload {...this.getProjectFileProps()}>
											Project文件
					          	</Upload>
									</Option>
									<Option value="1">
										<Upload {...this.getExcelFileProps()}>
											Excel文件
					          	</Upload>
									</Option>
								</Select>
							</div>
						</div>
					</Row>
					<div className="content-table">
						<Table emptyText={() => { return '暂无数据' }} bordered={true} data={tableData} columns={this.getColumns()} onRowClick={this.onRowClick} onExpand={this.onExpand} expandedRowKeys={this.state.expandedRowKeys}></Table>
					</div>
				</div>
			</App>
		)
	}
}